package com.kancy.publicapi.web.runner;

import com.kancy.publicapi.common.util.IPUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.Ordered;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;

@Slf4j
@Component
public class StartedUpRunner implements ApplicationRunner, Ordered {
    private static final String NOT_SET = "[Not Set]";
    @Autowired
    private Environment env;
    @Autowired
    private ConfigurableApplicationContext context;

    @Override
    public void run(ApplicationArguments args) {
        if (context.isActive()) {
            showApplicationSummary();
            log.info(" __    ___   _      ___   _     ____ _____  ____ ");
            log.info("/ /`  / / \\ | |\\/| | |_) | |   | |_   | |  | |_  ");
            log.info("\\_\\_, \\_\\_/ |_|  | |_|   |_|__ |_|__  |_|  |_|__ ");
            log.info("                                                      ");
            log.info("{}启动完毕，时间：{}" , env.getProperty("spring.application.name","系统"), LocalDateTime.now());
        }
    }

    private void showApplicationSummary() {
        String protocol = StringUtils.hasText(env.getProperty("server.ssl.key-store")) ? "https" : "http";
        String contextPath = env.getProperty("server.servlet.context-path");
        try {
            log.info("\n----------------------------------------------------------\n\t" +
                            "Application '{}' is running! \n\t" +
                            "Access URLs:\n\t" +
                            " - Local: {}://localhost:{}{}\n\t" +
                            " - External: {}://{}:{}{}\n\t" +
                            "Active Profile(s): {}\n" +
                            "----------------------------------------------------------",
                    env.getProperty("spring.application.name"), protocol, env.getProperty("server.port"), contextPath, protocol,
                    IPUtils.getIp(), env.getProperty("server.port"),contextPath, env.getActiveProfiles());
        } catch (Exception e) {
            log.warn(e.getMessage());
        }
    }

    @Override
    public int getOrder() {
        return Ordered.LOWEST_PRECEDENCE;
    }
}
